package com.ocom.srvpaccess.controller;


import com.ocom.common.constant.SrvpAccessDeviceUrl;
import com.ocom.common.entity.access.EntityMjDeviceInfo;
import com.ocom.common.entity.access.EntityMjDeviceInfoExtend;
import com.ocom.common.enums.MachEnum;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.utils.RespUtilMach;
import com.ocom.redis.util.RedisUtil;
import com.ocom.srvpaccess.service.MjDeviceInfoExtendService;
import com.ocom.srvpaccess.service.MjDeviceInfoService;
import com.ocom.srvpaccess.vo.DeviceFlagVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;


@RestController
public class DeviceFlagController {

    Logger log = LoggerFactory.getLogger(DeviceFlagController.class);

    @Autowired
    private MjDeviceInfoService mjDeviceInfoService;

    @Autowired
    private MjDeviceInfoExtendService mjDeviceInfoExtendService;

    @Resource
    private RedisUtil redisUtil;

    // 获取设备同步信息标志
    @GetMapping(value = SrvpAccessDeviceUrl.URLP_ACCESSDEVICE_getDeviceFlag)
    public RespMachMessage getDeviceFlag(Long companyId, String machNo, String versionCode,Integer commMode){

        //判断参数
        if (companyId == null){
            log.error("【{}】【{}】单位编号为空",machNo,companyId);
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        if (machNo==null){
            log.error("【{}】【{}】设备编号(出厂号)为空",machNo,companyId);
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        DeviceFlagVo deviceFlagVo = new DeviceFlagVo();
        //从设备信息表mj_device_info找到com_id ，device_no匹配的记录
        EntityMjDeviceInfo mjDeviceInfo = null;
        try {
            mjDeviceInfo = mjDeviceInfoService.getDeviceInfo(companyId, machNo);
            if (mjDeviceInfo == null){
                log.error("【{}】【{}】设备无数据或当前位置无记录",machNo,companyId);
                return RespUtilMach.error(MachEnum.MACH_NOT_MSG);
            }
        }catch (Exception exception){
            log.error("获取门禁设备信息失败"+exception.getMessage());
            return RespUtilMach.error(MachEnum.MACH_NOT_INFO);
        }


        //1.如果versionCode 不为空且不等于mj_device_info . app_ver：修改app_ver
        String appVer = mjDeviceInfo.getAppVer();
        if (!versionCode.isEmpty() && !versionCode.equals(appVer)){
            //更新数据
            try {
                mjDeviceInfoService.updateAppVer(companyId,machNo,versionCode);
            }catch (Exception exception){
                log.error("【{}】更新设备当前版本（设备上报）失败  ：【{}】",machNo,exception.getMessage());
                return RespUtilMach.error(MachEnum.NOT_APPVER);
            }
        }


        // 7.更新设备信息表mj_device_info.comm_mode=commMode；
        // 8.更新设备信息表mj_device_info.comm_time=当前时间。
        try {
            if(redisUtil.get("HttpMJMachCommTime:"+machNo)==null){
                mjDeviceInfoService.updateCommTimeCommMode(companyId,machNo,commMode);
            }
            redisUtil.set("HttpMJMachCommTime:"+machNo,new Date(),15000l);
//            if(!mjDeviceInfo.getCommMode().equals(commMode)){
//                mjDeviceInfoService.updateCommTimeCommMode(companyId,machNo,commMode);
//            }
        }catch (Exception exception){
            log.error("修改通讯时间或通信协议失败："+exception.getMessage());
        }



        //3.paramUpdate = mj_device_info . para_state == mj_device_info . 0 ? 0 : 1
        deviceFlagVo.setParamUpdate(mjDeviceInfo.getParaState());
        //4.acconpermissionUpdate = mj_device_info . group_ver == group_ver_tab ? 0 : 1
        if (mjDeviceInfo.getGroupVer().equals(mjDeviceInfo.getGroupVerTab())){
            deviceFlagVo.setAcconpermissionUpdate(0);
        }else {
            deviceFlagVo.setAcconpermissionUpdate(1);
        }

        //5.accontimeUpdate = mj_device_info . zone_ver == zone_ver_tab ? 0 : 1
        if (mjDeviceInfo.getZoneVer().equals(mjDeviceInfo.getZoneVerTab())){
            deviceFlagVo.setAccontimeUpdate(0);
        }else {
            deviceFlagVo.setAccontimeUpdate(1);
        }

        //6.listUpdate = mj_device_info . list_state == 0 ? 0 : 1
        deviceFlagVo.setListUpdate(mjDeviceInfo.getListState());
        //7.keyUpdate = mj_device_info . rsa_state == mj_device_info . 0 ? 0 : 1
        if (mjDeviceInfo.getRsaState() > 0){
            deviceFlagVo.setKeyUpdate(1L);
        }else {
            deviceFlagVo.setKeyUpdate(mjDeviceInfo.getRsaState());
        }

        return RespUtilMach.success(deviceFlagVo);
    }



    // 更新设备信息
    @PostMapping(value = SrvpAccessDeviceUrl.URLP_DEVICE_UPDATE_EXTEND_INFO)
    public RespMachMessage updateDeviceExtend(@RequestBody EntityMjDeviceInfoExtend entityMjDeviceInfoExtend){

        //判断参数
        if (entityMjDeviceInfoExtend.getComId() == null){
            log.error("单位编号为空");
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        if (entityMjDeviceInfoExtend.getDeviceNo()==null){
            log.error("设备编号(出厂号)为空");
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }

        mjDeviceInfoExtendService.saveExtendInfo(entityMjDeviceInfoExtend.getComId(),entityMjDeviceInfoExtend);

        return RespUtilMach.success();
    }


    // 更新设备信息
    @PostMapping(value = SrvpAccessDeviceUrl.URLP_DEVICE_GET_EXTEND_INFO)
    public RespMachMessage<EntityMjDeviceInfoExtend> getDeviceExtend(@RequestBody EntityMjDeviceInfoExtend entityMjDeviceInfoExtend){

        //判断参数
        if (entityMjDeviceInfoExtend.getComId() == null){
            log.error("单位编号为空");
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        if (entityMjDeviceInfoExtend.getDeviceNo()==null){
            log.error("设备编号(出厂号)为空");
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }

        return RespUtilMach.success(mjDeviceInfoExtendService.getExtendInfo( entityMjDeviceInfoExtend.getComId(),
                entityMjDeviceInfoExtend.getDeviceNo()));

    }

}
